﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
//using System.Windows.Forms;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.ComponentModel;


namespace Zephyr
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Constructor

        public MainWindow()
        {
            this.Icon = BitmapFrame.Create(new Uri("pack://application:,,,/Turtle.ico", UriKind.RelativeOrAbsolute));

            InitializeComponent();

            Connected(false);
                       
            System.ComponentModel.BackgroundWorker workerApplication = new System.ComponentModel.BackgroundWorker();
            workerApplication.DoWork += new System.ComponentModel.DoWorkEventHandler(MainWindow_Worker_DoWork);
            workerApplication.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(MainWindow_Worker_RunWorkerCompleted);
            workerApplication.RunWorkerAsync();

            _statusBar_ItemVersion.Content = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            _statusBar_ItemVersion.Content += " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }        
        private void MainWindow_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            // do start up tasks here in seperate thread to UI
        }
        private void MainWindow_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.Show();

            Login loginForm = new Login();
            loginForm.Owner = this;
            loginForm.ShowDialog();

            if (!loginForm.DialogResult.HasValue || !loginForm.DialogResult.Value)
            {
                this.Close();
                return;
            }

            _username = loginForm.Username;

            _zephyrLoader = new ZephyrLoader(_username);

            _combo_PricesGrouping.Items.Add(new ComboBoxItem() { Content = "Index & Sector" });
            _combo_PricesGrouping.Items.Add(new ComboBoxItem() { Content = "Index" });
            _combo_PricesGrouping.Items.Add(new ComboBoxItem() { Content = "Sector & Industry" });
            _combo_PricesGrouping.Items.Add(new ComboBoxItem() { Content = "Sector" });
            _combo_PricesGrouping.Items.Add(new ComboBoxItem() { Content = "None", IsSelected = true });

            _dataGrid_Prices.AutoGenerateColumns = false;
            _dataGrid_Prices.ItemsSource = _zephyrLoader.GridPriceMatrix;

            _dataGrid_SpikeArbSettings.AutoGenerateColumns = false;
            _dataGrid_SpikeArbSettings.ItemsSource = _zephyrLoader.GridSpikeArbSettings;
                        
            DataGridComboBoxColumn combo = new DataGridComboBoxColumn();
            combo.Header = "Exit";
            combo.ItemsSource = Enum.GetValues(typeof(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbStock.ExitPercentages));
            combo.SelectedValueBinding = new Binding("ExitPercentage");
            _dataGrid_SpikeArbSettings.Columns.Add(combo);
        }

        ZephyrLoader _zephyrLoader;
        string _username;

        #endregion

        public IDictionary<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity> Stocks
        {
            get { return new SortedDictionary<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>(Algobox.Apps.Finance.Zephyr.ZephyrApp.Stocks); }
        }

        private void Connected(bool isEnabled)
        {
            _button_SpikeLoad.IsEnabled = isEnabled;
            _button_TerrapinLoad.IsEnabled = isEnabled;
            _button_MossLoad.IsEnabled = isEnabled;
            _button_DastanLoad.IsEnabled = isEnabled;

            if (isEnabled)
            {
                _zephyrLoader.TradingFeed.OnTradingFeedShutdown += new Action(OnFeedShutdown);
                _zephyrLoader.MarketFeed.OnMarketFeedShutdown += new Action(OnFeedShutdown);

                //TERRAPIN
                _comboBox_TerrapinIndex.ItemsSource = Stocks.Select( a=> a.Value.Index).Distinct().ToArray();
                _comboBox_TerrapinStock.ItemsSource = Stocks;
                _comboBox_TerrapinStock.IsEnabled = true;
                _comboBox_TerrapinIndex.IsEnabled = true;
                _comboBox_TerrapinAccount.IsEnabled = true;
                _button_TerrapinAdd.IsEnabled = true;
                _dataGrid_TerrapinSettings.AutoGenerateColumns = false;
                _dataGrid_TerrapinSettings.ItemsSource = _zephyrLoader.GridTerrapinSettings;
                _dataGrid_TerrapinUnits.AutoGenerateColumns = false;
                _dataGrid_TerrapinUnits.ItemsSource = _zephyrLoader.GridTerrapinUnits;
                _dataGrid_TerrapinUnitSummary.AutoGenerateColumns = false;
                _dataGrid_TerrapinUnitSummary.ItemsSource = _zephyrLoader.GridTerrapinUnitSummary;

                // MOSS
                _comboBox_MossStock.ItemsSource = Stocks;
                _comboBox_MossStock.IsEnabled = true;
                _comboBox_MossAccount.IsEnabled = true;
                _button_MossAdd.IsEnabled = true;
                _dataGrid_MossSettings.AutoGenerateColumns = false;
                _dataGrid_MossSettings.ItemsSource = _zephyrLoader.GridMossSettings;
                _dataGrid_MossUnits.AutoGenerateColumns = false;
                _dataGrid_MossUnits.ItemsSource = _zephyrLoader.GridMossUnits;
                _dataGrid_MossUnitSummary.AutoGenerateColumns = false;
                _dataGrid_MossUnitSummary.ItemsSource = _zephyrLoader.GridMossUnitSummary;

                // DASTAN
                _comboBox_DastanStock.ItemsSource = Stocks;
                _comboBox_DastanIndex.ItemsSource = Stocks.Select(a => a.Value.Index).Distinct().ToArray();
                _comboBox_DastanStock.IsEnabled = true;
                _comboBox_DastanIndex.IsEnabled = true;
                _comboBox_DastanAccount.IsEnabled = true;
                _button_DastanAdd.IsEnabled = true;
                _dataGrid_DastanSettings.AutoGenerateColumns = false;
                _dataGrid_DastanSettings.ItemsSource = _zephyrLoader.GridDastanSettings;
                _dataGrid_DastanUnits.AutoGenerateColumns = false;
                _dataGrid_DastanUnits.ItemsSource = _zephyrLoader.GridDastanUnits;
                _dataGrid_DastanUnitSummary.AutoGenerateColumns = false;
                _dataGrid_DastanUnitSummary.ItemsSource = _zephyrLoader.GridDastanUnitSummary;

                // SPIKE
                _dataGrid_SpikeArb.AutoGenerateColumns = true;
                _dataGrid_SpikeArb.ItemsSource = _zephyrLoader.GridSpikeArbExecutions;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_zephyrLoader != null)
                _zephyrLoader.Exit();
        }

        private void Button_Exit(object sender, RoutedEventArgs e)
        {
            this.Close();
        }


        void OnFeedShutdown()
        {
            if (_zephyrLoader.IsSterlingTraderToggleOn)
            {
                _statusBar_ConnectionSterling.Dispatcher.BeginInvoke(new UpdateStatusBarConnectionDelegate(UpdateStatusBarConnection), _statusBar_ConnectionSterling, new SolidColorBrush(Colors.Tomato));
            }
            else if (_zephyrLoader.IsSterlingSimulationToggleOn)
            {
                _statusBar_ConnectionSterlingSimulation.Dispatcher.BeginInvoke(new UpdateStatusBarConnectionDelegate(UpdateStatusBarConnection), _statusBar_ConnectionSterlingSimulation, new SolidColorBrush(Colors.Tomato));

            }
            else if (_zephyrLoader.IsBatsReplayToggleOn)
            {
                _statusBar_ConnectionBatsReplay.Dispatcher.BeginInvoke(new UpdateStatusBarConnectionDelegate(UpdateStatusBarConnection), _statusBar_ConnectionBatsReplay, new SolidColorBrush(Colors.Tomato));
            }
        }

        public delegate void UpdateStatusBarConnectionDelegate(params object[] args);

        void UpdateStatusBarConnection(params object[] args)
        {
            ((Control)args[0]).Background = (Brush)args[1];
        }

        private void ComboBox_Account_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string account = ((ComboBoxItem)e.AddedItems[0]).Content as string;
            if (account != null && account != String.Empty)
            {
                if (sender == _comboBox_SpikeAccount)
                {
                    _zephyrLoader.SpikeArb_ChangeAccount(account);
                }
            }
        }

        #region Price Matrix

        private void ComboBoxPricesGrouping_SelectionChanged(object sender, SelectionChangedEventArgs e)
        { 
            _zephyrLoader.GridPriceMatrix.GroupDescriptions.Clear();
            _zephyrLoader.GridPriceMatrix.SortDescriptions.Clear();
            switch ((string)((ComboBoxItem)e.AddedItems[0]).Content)
            {
                case "Index & Sector":
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Index"));
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Sector"));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Index", System.ComponentModel.ListSortDirection.Ascending));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Sector", System.ComponentModel.ListSortDirection.Ascending));
                    break;
                case "Index":
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Index"));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Index", System.ComponentModel.ListSortDirection.Ascending));
                    break;
                case "Sector & Industry":
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Sector"));
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Industry"));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Sector", System.ComponentModel.ListSortDirection.Ascending));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Industry", System.ComponentModel.ListSortDirection.Ascending));
                    break;
                case "Sector":
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Sector"));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Sector", System.ComponentModel.ListSortDirection.Ascending));
                    break;
                case "None":
                    break;
                default:
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Index"));
                    _zephyrLoader.GridPriceMatrix.GroupDescriptions.Add(new PropertyGroupDescription("Sector"));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Index", System.ComponentModel.ListSortDirection.Ascending));
                    _zephyrLoader.GridPriceMatrix.SortDescriptions.Add(new System.ComponentModel.SortDescription("Sector", System.ComponentModel.ListSortDirection.Ascending));
                    break;
            }
        }

        #endregion
        
        #region Sterling Feed

        private void ButtonConnectSterling_Click(object sender, RoutedEventArgs e)
        {            
            _menu_ConnectSterling.IsChecked = true;
            _menu_ConnectBatsReplay.IsEnabled = false;
            _menu_ConnectSterling.IsEnabled = false;
            _menu_ConnectSterlingSimulation.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonConnectSterling_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonConnectSterling_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonConnectSterling_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = _zephyrLoader.Connect_Sterling();
        }
        private void ButtonConnectSterling_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || !(bool)e.Result)
            {
                _statusBar_ConnectionSterling.Background = new SolidColorBrush(Colors.Tomato);
            }
            else
            {
                _statusBar_ConnectionSterling.Background = new SolidColorBrush(Colors.YellowGreen);
                Connected(true);
            }
        }


        private void ButtonConnectSterlingSimulation_Click(object sender, RoutedEventArgs e)
        {
            _menu_ConnectSterlingSimulation.IsChecked = true;
            _menu_ConnectBatsReplay.IsEnabled = false;
            _menu_ConnectSterling.IsEnabled = false;
            _menu_ConnectSterlingSimulation.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonConnectSterlingSimulation_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonConnectSterlingSimulation_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonConnectSterlingSimulation_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = _zephyrLoader.Connect_SterlingSimulation();
        }
        private void ButtonConnectSterlingSimulation_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || !(bool)e.Result)
            {
                _statusBar_ConnectionSterlingSimulation.Background = new SolidColorBrush(Colors.Tomato);
            }
            else
            {
                _statusBar_ConnectionSterlingSimulation.Background = new SolidColorBrush(Colors.YellowGreen);
                Connected(true);
            }
        }
        
        #endregion

        #region Bats File Feed

        MenuItem _menu_BatsReplayLoadFile;

        private void ButtonConnectBatsReplay_Click(object sender, RoutedEventArgs e)
        {
            NLog.LogManager.GlobalThreshold = NLog.LogLevel.Error;
            NLog.LogManager.ReconfigExistingLoggers();

            _menu_ConnectBatsReplay.Click -= new RoutedEventHandler(ButtonConnectBatsReplay_Click);
            _menu_ConnectSterling.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonConnectBatsReplay_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonConnectBatsReplay_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonConnectBatsReplay_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            e.Result = _zephyrLoader.Connect_BatsReplay();
        }
        private void ButtonConnectBatsReplay_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || !(bool)e.Result)
            {
                _statusBar_ConnectionBatsReplay.Background = new SolidColorBrush(Colors.Tomato);
            }
            else
            {
                _menu_BatsReplayLoadFile = new MenuItem();
                _menu_BatsReplayLoadFile.Header = "Load File";
                _menu_BatsReplayLoadFile.Click += new RoutedEventHandler(ButtonBatsReplayLoadFile_Click);
                _menu_ConnectBatsReplay.Items.Add(_menu_BatsReplayLoadFile);

                _menu_BatsReplayLoadFile.IsEnabled = true;
                _statusBar_ConnectionBatsReplay.Background = new SolidColorBrush(Colors.YellowGreen);
                Connected(true);
            }
        }

        private void ButtonBatsReplayLoadFile_Click(object sender, RoutedEventArgs e)
        {
            _menu_ConnectBatsReplay.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonBatsReplayLoadFile_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonBatsReplayLoadFile_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }
        private void ButtonBatsReplayLoadFile_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {            
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".gz"; // Default file extension
            dlg.Filter = "GZip compressed files (.gz)|*.gz"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                _zephyrLoader.BatsReplay_LoadFile(dlg.FileName);
                e.Result = dlg.FileName;
                return;
            }          
            
            e.Result = null;            
        }
        private void ButtonBatsReplayLoadFile_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null && e.Result is String)
            {
                MenuItem item = new MenuItem() { Header = (string)e.Result };
                item.Click += new RoutedEventHandler(ButtonBatsReplayLoadFileSpecific_Click);
                _menu_ConnectBatsReplay.Items.Add(item);
            }
            _menu_ConnectBatsReplay.IsEnabled = true;
        }

        private void ButtonBatsReplayLoadFileSpecific_Click(object sender, RoutedEventArgs e)
        {
            _menu_ConnectBatsReplay.IsEnabled = false;

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonBatsReplayLoadFileSpecific_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonBatsReplayLoadFileSpecific_Worker_RunWorkerCompleted);
            worker.RunWorkerAsync((string)((MenuItem)sender).Header);
        }
        private void ButtonBatsReplayLoadFileSpecific_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument is String)
            {
                string filename = (string)e.Argument;
                _zephyrLoader.BatsReplay_LoadFile(filename);
            }
        }
        private void ButtonBatsReplayLoadFileSpecific_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _menu_ConnectBatsReplay.IsEnabled = true;
        }

        #endregion
        
        #region Spike Settings

        private void ButtonSpikeSave_Click(object sender, RoutedEventArgs e)
        {
            _button_SpikeSave.Content = "Saving";
            _button_SpikeSave.IsEnabled = false;
            System.ComponentModel.BackgroundWorker workerSpikeArbConfigSave = new System.ComponentModel.BackgroundWorker();
            workerSpikeArbConfigSave.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonSpikeSave_Worker_DoWork);
            workerSpikeArbConfigSave.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonSpikeSave_Worker_RunWorkerCompleted);
            // Run the Background Worker
            workerSpikeArbConfigSave.RunWorkerAsync();
        }
        private void ButtonSpikeSave_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            _zephyrLoader.SpikeArb_SaveSettings();
        }
        private void ButtonSpikeSave_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _button_SpikeSave.Content = "Timeout";
                Thread.Sleep(2000);
                _button_SpikeSave.Content = "Save";
                _button_SpikeSave.IsEnabled = true;
            }
            else if (e.Error != null)
            {
                _button_SpikeSave.Content = "Error";
                Thread.Sleep(2000);
                _button_SpikeSave.Content = "Save";
                _button_SpikeSave.IsEnabled = true;
            }
            else
            {
                _button_SpikeSave.Content = "Saved";
                Thread.Sleep(2000);
                _button_SpikeSave.Content = "Save";
                _button_SpikeSave.IsEnabled = true;
            }
        }

        private void ButtonSpikeStart_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_SpikeLoad)
            {
                _button_SpikeLoad.IsEnabled = false;
                System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonSpikeStart_Worker_DoWork);
                worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonSpikeStart_Worker_RunWorkerCompleted);

                if (_button_SpikeLoad.Content.ToString() == "Load")
                {
                    _comboBox_SpikeAccount.IsEnabled = false;
                    _button_SpikeLoad.Content = "Loading";
                    worker.RunWorkerAsync("Loading");
                }
                else if (_button_SpikeLoad.Content.ToString() == "Unload")
                {
                    if (_checkBox_SpikePausePrimary.IsChecked.Value)
                        _checkBox_SpikePausePrimary.IsChecked = false;
                    if (_checkBox_SpikePauseChix.IsChecked.Value)
                        _checkBox_SpikePauseChix.IsChecked = false;
                    if (_checkBox_SpikePauseBats.IsChecked.Value)
                        _checkBox_SpikePauseBats.IsChecked = false;
                    if (_checkBox_SpikePauseCollar1.IsChecked.Value)
                        _checkBox_SpikePauseCollar1.IsChecked = false;
                    if (_checkBox_SpikePauseCollar2.IsChecked.Value)
                        _checkBox_SpikePauseCollar2.IsChecked = false;
                    if (_checkBox_SpikePauseCollar3.IsChecked.Value)
                        _checkBox_SpikePauseCollar3.IsChecked = false;
                    if (_checkBox_SpikePauseCollar4.IsChecked.Value)
                        _checkBox_SpikePauseCollar4.IsChecked = false;

                    _checkBox_SpikePausePrimary.IsEnabled = false;
                    _checkBox_SpikePauseChix.IsEnabled = false;
                    _checkBox_SpikePauseBats.IsEnabled = false;
                    _checkBox_SpikePauseCollar1.IsEnabled = false;
                    _checkBox_SpikePauseCollar2.IsEnabled = false;
                    _checkBox_SpikePauseCollar3.IsEnabled = false;
                    _checkBox_SpikePauseCollar4.IsEnabled = false;

                    _button_SpikeLoad.Content = "Unloading";
                    worker.RunWorkerAsync("Unloading");
                }
            }
        }
        private void ButtonSpikeStart_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument.ToString() == "Loading")
            {
                if (!_zephyrLoader.SpikeArb_LoadSettings())
                    e.Cancel = true;
            }
            else if (e.Argument.ToString() == "Unloading")
            {
                _zephyrLoader.SpikeArb_UnloadSettings();
            }

            e.Result = e.Argument;
        }
        private void ButtonSpikeStart_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _button_SpikeLoad.Content = "Failed";
                _button_SpikeSave.IsEnabled = false;
                return;
            }

            if (e.Result.ToString() == "Loading")
            {
                _button_SpikeSave.IsEnabled = true;
                _button_SpikeLoad.IsEnabled = true;
                _button_SpikeLoad.Content = "Unload";

                _checkBox_SpikePausePrimary.IsEnabled = true;
                _checkBox_SpikePauseChix.IsEnabled = true;
                _checkBox_SpikePauseBats.IsEnabled = true;
                _checkBox_SpikePauseCollar1.IsEnabled = true;
                _checkBox_SpikePauseCollar2.IsEnabled = true;
                _checkBox_SpikePauseCollar3.IsEnabled = true;
                _checkBox_SpikePauseCollar4.IsEnabled = true;
            }
            else if (e.Result.ToString() == "Unloading")
            {
                _button_SpikeLoad.IsEnabled = true;
                _button_SpikeSave.IsEnabled = false;
                _button_SpikeLoad.Content = "Load";
                _comboBox_SpikeAccount.IsEnabled = true;

            }

        }
        
        private void CheckBoxSpikePause_Checked(object sender, RoutedEventArgs e)
        {
            if (sender == _checkBox_SpikePausePrimary
                || sender == _checkBox_SpikePauseChix
                || sender == _checkBox_SpikePauseBats
                || sender == _checkBox_SpikePauseCollar1
                || sender == _checkBox_SpikePauseCollar2
                || sender == _checkBox_SpikePauseCollar3
                || sender == _checkBox_SpikePauseCollar4)
            {
                System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                worker.DoWork += new System.ComponentModel.DoWorkEventHandler(CheckBoxSpikePause_Worker_DoWork);
                worker.RunWorkerAsync(sender);
            }
        }
        private void CheckBoxSpikePause_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument is CheckBox)
            {
                if (e.Argument == _checkBox_SpikePausePrimary)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Primary);
                else if (e.Argument == _checkBox_SpikePauseChix)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Chix);
                else if (e.Argument == _checkBox_SpikePauseBats)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Bats);
                else if (e.Argument == _checkBox_SpikePauseCollar1)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Collar1);
                else if (e.Argument == _checkBox_SpikePauseCollar2)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Collar2);
                else if (e.Argument == _checkBox_SpikePauseCollar3)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Collar3);
                else if (e.Argument == _checkBox_SpikePauseCollar4)
                    _zephyrLoader.SpikeArb_Pause(Algobox.Structure.Finance.Strategies.SpikeArb.SpikeArbManagement.Pause.Collar4);
            }
        }
        
        #endregion

        #region Terrapin Settings

        private void ButtonTerrapinAdd_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_TerrapinAdd)
            {
                int value, entry, exit, period;

                if (_comboBox_TerrapinAccount.SelectedItem != null
                    && _comboBox_TerrapinAccount.SelectedItem is ComboBoxItem
                    && Int32.TryParse(_textBox_TerrapinValue.Text, out value)
                    && Int32.TryParse(_textBox_TerrapinEntry.Text, out entry)
                    && Int32.TryParse(_textBox_TerrapinExit.Text, out exit)
                    && Int32.TryParse(_textBox_TerrapinAverage.Text, out period)
                    && value > 0 && entry > 1 && exit > 1 && period > 1)
                {
                    BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

                    if (_comboBox_TerrapinStock.SelectedItem != null
                        && _comboBox_TerrapinStock.SelectedItem is KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>)
                    {
                        _comboBox_TerrapinIndex.IsEnabled = false;
                        _comboBox_TerrapinStock.IsEnabled = false;
                        _comboBox_TerrapinAccount.IsEnabled = false;
                        _button_TerrapinAdd.IsEnabled = false;
                        _button_TerrapinLoad.IsEnabled = false;
                        _button_TerrapinSave.IsEnabled = false;

                        KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity> pair = (KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>)_comboBox_TerrapinStock.SelectedItem;
                        
                        worker.DoWork += new DoWorkEventHandler(ButtonTerrapinAdd_Worker_DoWork);
                        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ButtonTerrapinAdd_Worker_RunWorkerCompleted);

                        var data = new Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string, int, int, int, int>(
                            (Algobox.Objects.Finance.Assets.Stock.StockSecurity)pair.Value, 
                            ((ComboBoxItem)_comboBox_TerrapinAccount.SelectedItem).Content.ToString(), 
                            value, 
                            entry, 
                            exit, 
                            period);

                        worker.RunWorkerAsync(data);

                    }
                    else if (_comboBox_TerrapinIndex.SelectedItem != null
                        && _comboBox_TerrapinIndex.SelectedItem is string)
                    {
                        _comboBox_TerrapinIndex.IsEnabled = false;
                        _comboBox_TerrapinStock.IsEnabled = false;
                        _comboBox_TerrapinAccount.IsEnabled = false;
                        _button_TerrapinAdd.IsEnabled = false;
                        _button_TerrapinLoad.IsEnabled = false;
                        _button_TerrapinSave.IsEnabled = false;

                        worker.DoWork += new DoWorkEventHandler(ButtonTerrapinAdd_Worker_DoWorkMultiple);
                        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ButtonTerrapinAdd_Worker_RunWorkerCompleted);
                        string selectedIndex = (string)_comboBox_TerrapinIndex.SelectedItem;
                        var data2 = new Tuple<IEnumerable<Algobox.Objects.Finance.Assets.Stock.StockSecurity>, string, int, int, int, int>(
                            Stocks.Values.Where(a => a.Index == selectedIndex),
                            ((ComboBoxItem)_comboBox_TerrapinAccount.SelectedItem).Content.ToString(),
                            value,
                            entry,
                            exit,
                            period);

                        worker.RunWorkerAsync(data2);

                    }
                }
            }
        }
        private void ButtonTerrapinAdd_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var data = e.Argument as Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string, int, int, int, int>;

            _zephyrLoader.Terrapin_Add(data.Item1, data.Item2, data.Item3, data.Item4, data.Item5, data.Item6);
        }
        private void ButtonTerrapinAdd_Worker_DoWorkMultiple(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var data = e.Argument as Tuple<IEnumerable<Algobox.Objects.Finance.Assets.Stock.StockSecurity>, string, int, int, int, int>;

            _zephyrLoader.Terrapin_Add(data.Item1, data.Item2, data.Item3, data.Item4, data.Item5, data.Item6);
        }
        private void ButtonTerrapinAdd_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _comboBox_TerrapinStock.IsEnabled = true;
            _comboBox_TerrapinIndex.IsEnabled = true;
            _comboBox_TerrapinAccount.IsEnabled = true;
            _button_TerrapinAdd.IsEnabled = true;
            _button_TerrapinLoad.IsEnabled = true;
            _button_TerrapinSave.IsEnabled = true;
            _dataGrid_TerrapinSettings.UpdateLayout();
        }

        private void ButtonTerrapinLoad_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_TerrapinLoad)
            {
                _button_TerrapinLoad.IsEnabled = false;
                System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonTerrapinLoad_Worker_DoWork);
                worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonTerrapinLoad_Worker_RunWorkerCompleted);

                if (_button_TerrapinLoad.Content.ToString() == "Load")
                {
                    _button_TerrapinLoad.Content = "Loading";
                    worker.RunWorkerAsync("Loading");
                }
                else if (_button_TerrapinLoad.Content.ToString() == "Unload")
                {
                    _button_TerrapinSave.IsEnabled = false;
                    _button_TerrapinLoad.Content = "Unloading";
                    worker.RunWorkerAsync("Unloading");
                    _comboBox_TerrapinIndex.IsEnabled = false;
                    _comboBox_TerrapinStock.IsEnabled = false;
                    _comboBox_TerrapinAccount.IsEnabled = false;
                    _button_TerrapinAdd.IsEnabled = false;
                }
            }
        }
        private void ButtonTerrapinLoad_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument.ToString() == "Loading")
            {
                if (!_zephyrLoader.Terrapin_LoadSettings())
                    e.Cancel = true;
            }
            else if (e.Argument.ToString() == "Unloading")
            {
                _zephyrLoader.Terrapin_UnloadSettings();
            }
            e.Result = e.Argument;
        }
        private void ButtonTerrapinLoad_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                _button_TerrapinLoad.Content = "Failed";
                _button_TerrapinSave.IsEnabled = false;
                return;
            }

            if (e.Result.ToString() == "Loading")
            {
                _button_TerrapinLoad.IsEnabled = true;
                _button_TerrapinSave.IsEnabled = true;
                _button_TerrapinLoad.Content = "Unload";
                _comboBox_TerrapinStock.IsEnabled = true;
                _comboBox_TerrapinIndex.IsEnabled = true;
                _comboBox_TerrapinAccount.IsEnabled = true;
                _button_TerrapinAdd.IsEnabled = true;
            }
            else if (e.Result.ToString() == "Unloading")
            {
                _button_TerrapinSave.IsEnabled = false;
                _button_TerrapinLoad.IsEnabled = true;
                _button_TerrapinLoad.Content = "Load";
            }
        }
        
        private void ButtonTerrapinSave_Click(object sender, RoutedEventArgs e)
        {
            _button_TerrapinSave.Content = "Saving";
            _button_TerrapinSave.IsEnabled = false;
            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonTerrapinSave_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonTerrapinSave_Worker_RunWorkerCompleted);
            // Run the Background Worker
            worker.RunWorkerAsync();
        }
        private void ButtonTerrapinSave_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            _zephyrLoader.Terrapin_SaveSettings();
        }
        private void ButtonTerrapinSave_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _button_TerrapinSave.Content = "Timeout";
            }
            else if (e.Error != null)
            {
                _button_TerrapinSave.Content = "Error";
            }
            else
            {
                _button_TerrapinSave.Content = "Save";
            }
            _button_TerrapinSave.IsEnabled = true;
        }
        

        private void ButtonTerrapinClosePosition_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Terrapin.TerrapinStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Terrapin.TerrapinStock;
            if (strategy != null)
            {
                strategy.ExitUnit(DateTime.Now);
            }
        }
        private void ButtonTerrapinRemove_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Terrapin.TerrapinStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Terrapin.TerrapinStock;
            if (strategy != null)
            {
                _zephyrLoader.Terrapin_Remove(strategy);
            }
        }
        
        private void ComboBox_TerrapinStock_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(((ComboBox)sender).IsDropDownOpen)
                _comboBox_TerrapinIndex.SelectedIndex = -1;
            e.Handled = true;
        }

        private void ComboBox_TerrapinIndex_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).IsDropDownOpen) 
                _comboBox_TerrapinStock.SelectedIndex = -1;
            e.Handled = true;
        }                

        #endregion

        #region Moss Settings

        private void ButtonMossAdd_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_MossAdd)
            {
                if (_comboBox_MossStock.SelectedItem != null
                    && _comboBox_MossStock.SelectedItem is KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>
                    && _comboBox_MossAccount.SelectedItem != null
                    && _comboBox_MossAccount.SelectedItem is ComboBoxItem)
                {
                    System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                    worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonMossAdd_Worker_DoWork);
                    worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonMossAdd_Worker_RunWorkerCompleted);

                    _comboBox_MossStock.IsEnabled = false;
                    _comboBox_MossAccount.IsEnabled = false;
                    _button_MossAdd.IsEnabled = false;
                    _button_MossLoad.IsEnabled = false;
                    _button_MossSave.IsEnabled = false;

                    KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity> pair = (KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>)_comboBox_MossStock.SelectedItem;

                    Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string> data =
                        new Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string>(
                            (Algobox.Objects.Finance.Assets.Stock.StockSecurity)pair.Value,
                            ((ComboBoxItem)_comboBox_MossAccount.SelectedItem).Content.ToString());

                    worker.RunWorkerAsync(data);
                }
            }
        }
        private void ButtonMossAdd_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string> data = e.Argument as Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string>;

            _zephyrLoader.Moss_Add(data.Item1, data.Item2);
            //System.Diagnostics.Debug.WriteLine("Symbol:" + sender.ToString());
            //_zephyrLoader.MossAdd();
        }
        private void ButtonMossAdd_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _comboBox_MossStock.IsEnabled = true;
            _comboBox_MossAccount.IsEnabled = true;
            _button_MossAdd.IsEnabled = true;
            _button_MossLoad.IsEnabled = true;
            _button_MossSave.IsEnabled = true;
        }

        private void ButtonMossLoad_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_MossLoad)
            {
                _button_MossLoad.IsEnabled = false;
                System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonMossLoad_Worker_DoWork);
                worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonMossLoad_Worker_RunWorkerCompleted);

                if (_button_MossLoad.Content.ToString() == "Load")
                {
                    _button_MossLoad.Content = "Loading";
                    worker.RunWorkerAsync("Loading");
                }
                else if (_button_MossLoad.Content.ToString() == "Unload")
                {
                    _button_MossSave.IsEnabled = false;
                    _button_MossLoad.Content = "Unloading";
                    worker.RunWorkerAsync("Unloading");
                    _comboBox_MossStock.IsEnabled = false;
                    _comboBox_MossAccount.IsEnabled = false;
                    _button_MossAdd.IsEnabled = false;
                }
            }
        }
        private void ButtonMossLoad_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument.ToString() == "Loading")
            {
                if (!_zephyrLoader.Moss_LoadSettings())
                    e.Cancel = true;
            }
            else if (e.Argument.ToString() == "Unloading")
            {
                _zephyrLoader.Moss_UnloadSettings();
            }
            e.Result = e.Argument;
        }
        private void ButtonMossLoad_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                _button_MossLoad.Content = "Failed";
                _button_MossSave.IsEnabled = false;
                return;
            }

            if (e.Result.ToString() == "Loading")
            {
                _button_MossLoad.IsEnabled = true;
                _button_MossSave.IsEnabled = true;
                _button_MossLoad.Content = "Unload";
            }
            else if (e.Result.ToString() == "Unloading")
            {
                _button_MossSave.IsEnabled = false;
                _button_MossLoad.IsEnabled = true;
                _button_MossLoad.Content = "Load";
            }
        }

        private void ButtonMossSave_Click(object sender, RoutedEventArgs e)
        {
            _button_MossSave.Content = "Saving";
            _button_MossSave.IsEnabled = false;
            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonMossSave_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonMossSave_Worker_RunWorkerCompleted);
            // Run the Background Worker
            worker.RunWorkerAsync();
        }
        private void ButtonMossSave_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            _zephyrLoader.Moss_SaveSettings();
        }
        private void ButtonMossSave_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _button_MossSave.Content = "Timeout";
            }
            else if (e.Error != null)
            {
                _button_MossSave.Content = "Error";
            }
            else
            {
                _button_MossSave.Content = "Save";
            }
            _button_MossSave.IsEnabled = true;
        }

        private void ButtonMossRemove_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Moss.MossStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Moss.MossStock;
            if (strategy != null)
            {
                _zephyrLoader.Moss_Remove(strategy);
            }
        }

        #endregion

        #region Dastan Settings

        /*

        private void ButtonDastanAdd_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_DastanAdd)
            {
                if (_comboBox_DastanStock.SelectedItem != null
                    && _comboBox_DastanStock.SelectedItem is KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>
                    && _comboBox_DastanAccount.SelectedItem != null
                    && _comboBox_DastanAccount.SelectedItem is ComboBoxItem)
                {
                    System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                    worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonDastanAdd_Worker_DoWork);
                    worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonDastanAdd_Worker_RunWorkerCompleted);

                    _comboBox_DastanStock.IsEnabled = false;
                    _comboBox_DastanAccount.IsEnabled = false;
                    _button_DastanAdd.IsEnabled = false;
                    _button_DastanLoad.IsEnabled = false;
                    _button_DastanSave.IsEnabled = false;

                    KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity> pair = (KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>)_comboBox_DastanStock.SelectedItem;

                    Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string> data =
                        new Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string>(
                            (Algobox.Objects.Finance.Assets.Stock.StockSecurity)pair.Value,
                            ((ComboBoxItem)_comboBox_DastanAccount.SelectedItem).Content.ToString());

                    worker.RunWorkerAsync(data);
                }
            }
        }
        private void ButtonDastanAdd_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string> data = e.Argument as Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string>;

            _zephyrLoader.Dastan_Add(data.Item1, data.Item2);
            //System.Diagnostics.Debug.WriteLine("Symbol:" + sender.ToString());
            //_zephyrLoader.DastanAdd();
        }
        private void ButtonDastanAdd_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _comboBox_DastanStock.IsEnabled = true;
            _comboBox_DastanAccount.IsEnabled = true;
            _button_DastanAdd.IsEnabled = true;
            _button_DastanLoad.IsEnabled = true;
            _button_DastanSave.IsEnabled = true;
        }

        private void ButtonDastanLoad_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_DastanLoad)
            {
                _dataGrid_DastanSettings.AutoGenerateColumns = false;
                _dataGrid_DastanSettings.ItemsSource = _zephyrLoader.GridDastanSettings;

                _button_DastanLoad.IsEnabled = false;
                System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonDastanLoad_Worker_DoWork);
                worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonDastanLoad_Worker_RunWorkerCompleted);

                if (_button_DastanLoad.Content.ToString() == "Load")
                {
                    _button_DastanLoad.Content = "Loading";
                    worker.RunWorkerAsync("Loading");
                }
                else if (_button_DastanLoad.Content.ToString() == "Unload")
                {
                    _button_DastanSave.IsEnabled = false;
                    _button_DastanLoad.Content = "Unloading";
                    worker.RunWorkerAsync("Unloading");
                    _comboBox_DastanStock.IsEnabled = false;
                    _comboBox_DastanAccount.IsEnabled = false;
                    _button_DastanAdd.IsEnabled = false;
                }

                _dataGrid_DastanUnits.AutoGenerateColumns = false;
                _dataGrid_DastanUnits.ItemsSource = _zephyrLoader.GridDastanUnits;

                _dataGrid_DastanUnitSummary.AutoGenerateColumns = false;
                _dataGrid_DastanUnitSummary.ItemsSource = _zephyrLoader.GridDastanUnitSummary;
            }
        }
        private void ButtonDastanLoad_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument.ToString() == "Loading")
            {
                if (!_zephyrLoader.Dastan_LoadSettings())
                    e.Cancel = true;
            }
            else if (e.Argument.ToString() == "Unloading")
            {
                _zephyrLoader.Dastan_UnloadSettings();
            }
            e.Result = e.Argument;
        }
        private void ButtonDastanLoad_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                _button_DastanLoad.Content = "Failed";
                _button_DastanSave.IsEnabled = false;
                return;
            }

            if (e.Result.ToString() == "Loading")
            {
                _button_DastanLoad.IsEnabled = true;
                _button_DastanSave.IsEnabled = true;
                _button_DastanLoad.Content = "Unload";
                _comboBox_DastanStock.IsEnabled = true;
                _comboBox_DastanAccount.IsEnabled = true;
                _button_DastanAdd.IsEnabled = true;
            }
            else if (e.Result.ToString() == "Unloading")
            {
                _button_DastanSave.IsEnabled = false;
                _button_DastanLoad.IsEnabled = true;
                _button_DastanLoad.Content = "Load";
            }
        }

        private void ButtonDastanSave_Click(object sender, RoutedEventArgs e)
        {
            _button_DastanSave.Content = "Saving";
            _button_DastanSave.IsEnabled = false;
            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonDastanSave_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonDastanSave_Worker_RunWorkerCompleted);
            // Run the Background Worker
            worker.RunWorkerAsync();
        }
        private void ButtonDastanSave_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            _zephyrLoader.Dastan_SaveSettings();
        }
        private void ButtonDastanSave_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _button_DastanSave.Content = "Timeout";
            }
            else if (e.Error != null)
            {
                _button_DastanSave.Content = "Error";
            }
            else
            {
                _button_DastanSave.Content = "Save";
            }
            _button_DastanSave.IsEnabled = true;
        }


        private void ButtonDastanClosePosition_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Dastan.DastanStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Dastan.DastanStock;
            if (strategy != null)
            {
                strategy.ExitUnit(DateTime.Now);
            }
        }
        private void ButtonDastanRemove_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Dastan.DastanStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Dastan.DastanStock;
            if (strategy != null)
            {
                _zephyrLoader.Dastan_Remove(strategy);
            }
        }
        */

        private void ButtonDastanAdd_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_DastanAdd)
            {
                int value, entry, exit, period, ticks;

                if (_comboBox_DastanAccount.SelectedItem != null
                    && _comboBox_DastanAccount.SelectedItem is ComboBoxItem
                    && Int32.TryParse(_textBox_DastanValue.Text, out value)
                    && Int32.TryParse(_textBox_DastanEntry.Text, out entry)
                    && Int32.TryParse(_textBox_DastanExit.Text, out exit)
                    && Int32.TryParse(_textBox_DastanAverage.Text, out period)
                    && Int32.TryParse(_textBox_DastanTickCount.Text, out ticks)
                    && value > 0 && entry > 1 && exit > 1 && period > 1)
                {
                    BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                    
                    if (_comboBox_DastanStock.SelectedItem != null
                        && _comboBox_DastanStock.SelectedItem is KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>)
                    {
                        _comboBox_DastanIndex.IsEnabled = false;
                        _comboBox_DastanStock.IsEnabled = false;
                        _comboBox_DastanAccount.IsEnabled = false;
                        _button_DastanAdd.IsEnabled = false;
                        _button_DastanLoad.IsEnabled = false;
                        _button_DastanSave.IsEnabled = false;

                        worker.DoWork += new DoWorkEventHandler(ButtonDastanAdd_Worker_DoWork);
                        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ButtonDastanAdd_Worker_RunWorkerCompleted);

                        var data =
                            new Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string, int, int, int, int, int>(
                                (Algobox.Objects.Finance.Assets.Stock.StockSecurity)((KeyValuePair<string, Algobox.Objects.Finance.Assets.Stock.StockSecurity>)_comboBox_DastanStock.SelectedItem).Value,
                                ((ComboBoxItem)_comboBox_DastanAccount.SelectedItem).Content.ToString(),
                                value,
                                entry,
                                exit,
                                period,
                                ticks);

                        worker.RunWorkerAsync(data);
                        
                    }
                    else if (_comboBox_DastanIndex.SelectedItem != null
                        && _comboBox_DastanIndex.SelectedItem is string)
                    {
                        _comboBox_DastanIndex.IsEnabled = false;
                        _comboBox_DastanStock.IsEnabled = false;
                        _comboBox_DastanAccount.IsEnabled = false;
                        _button_DastanAdd.IsEnabled = false;
                        _button_DastanLoad.IsEnabled = false;
                        _button_DastanSave.IsEnabled = false;

                        worker.DoWork += new DoWorkEventHandler(ButtonDastanAdd_Worker_DoWorkMultiple);
                        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ButtonDastanAdd_Worker_RunWorkerCompleted);
                        
                        string selectedIndex = (string)_comboBox_DastanIndex.SelectedItem;
                            
                        var data2 =
                            new Tuple<IEnumerable<Algobox.Objects.Finance.Assets.Stock.StockSecurity>, string, int, int, int, int, int>(
                                Stocks.Values.Where(a => a.Index == selectedIndex),
                                ((ComboBoxItem)_comboBox_DastanAccount.SelectedItem).Content.ToString(),
                                value,
                                entry,
                                exit,
                                period,
                                ticks);

                        worker.RunWorkerAsync(data2);                        
                    }
                }
            }
        }
        private void ButtonDastanAdd_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var data = e.Argument as Tuple<Algobox.Objects.Finance.Assets.Stock.StockSecurity, string, int, int, int, int, int>;

            _zephyrLoader.Dastan_Add(data.Item1, data.Item2, data.Item3, data.Item4, data.Item5, data.Item6, data.Item7);
        }
        private void ButtonDastanAdd_Worker_DoWorkMultiple(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var data = e.Argument as Tuple<IEnumerable<Algobox.Objects.Finance.Assets.Stock.StockSecurity>, string, int, int, int, int, int>;

            _zephyrLoader.Dastan_Add(data.Item1, data.Item2, data.Item3, data.Item4, data.Item5, data.Item6, data.Item7);
        }
        private void ButtonDastanAdd_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _comboBox_DastanStock.IsEnabled = true;
            _comboBox_DastanIndex.IsEnabled = true;
            _comboBox_DastanAccount.IsEnabled = true;
            _button_DastanAdd.IsEnabled = true;
            _button_DastanLoad.IsEnabled = true;
            _button_DastanSave.IsEnabled = true;
        }

        private void ButtonDastanLoad_Click(object sender, RoutedEventArgs e)
        {
            if (sender == _button_DastanLoad)
            {
                _button_DastanLoad.IsEnabled = false;
                System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonDastanLoad_Worker_DoWork);
                worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonDastanLoad_Worker_RunWorkerCompleted);

                if (_button_DastanLoad.Content.ToString() == "Load")
                {
                    _button_DastanLoad.Content = "Loading";
                    worker.RunWorkerAsync("Loading");
                }
                else if (_button_DastanLoad.Content.ToString() == "Unload")
                {
                    _button_DastanSave.IsEnabled = false;
                    _button_DastanLoad.Content = "Unloading";
                    worker.RunWorkerAsync("Unloading");
                    _comboBox_DastanIndex.IsEnabled = false;
                    _comboBox_DastanStock.IsEnabled = false;
                    _comboBox_DastanAccount.IsEnabled = false;
                    _button_DastanAdd.IsEnabled = false;
                }
            }
        }
        private void ButtonDastanLoad_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (e.Argument.ToString() == "Loading")
            {
                if (!_zephyrLoader.Dastan_LoadSettings())
                    e.Cancel = true;
            }
            else if (e.Argument.ToString() == "Unloading")
            {
                _zephyrLoader.Dastan_UnloadSettings();
            }
            e.Result = e.Argument;
        }
        private void ButtonDastanLoad_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                _button_DastanLoad.Content = "Failed";
                _button_DastanSave.IsEnabled = false;
                return;
            }

            if (e.Result.ToString() == "Loading")
            {
                _button_DastanLoad.IsEnabled = true;
                _button_DastanSave.IsEnabled = true;
                _button_DastanLoad.Content = "Unload";
                _comboBox_DastanStock.IsEnabled = true;
                _comboBox_DastanIndex.IsEnabled = true;
                _comboBox_DastanAccount.IsEnabled = true;
                _button_DastanAdd.IsEnabled = true;
            }
            else if (e.Result.ToString() == "Unloading")
            {
                _button_DastanSave.IsEnabled = false;
                _button_DastanLoad.IsEnabled = true;
                _button_DastanLoad.Content = "Load";
            }
        }
        
        private void ButtonDastanSave_Click(object sender, RoutedEventArgs e)
        {
            _button_DastanSave.Content = "Saving";
            _button_DastanSave.IsEnabled = false;
            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ButtonDastanSave_Worker_DoWork);
            worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(ButtonDastanSave_Worker_RunWorkerCompleted);
            // Run the Background Worker
            worker.RunWorkerAsync();
        }
        private void ButtonDastanSave_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            _zephyrLoader.Dastan_SaveSettings();
        }
        private void ButtonDastanSave_Worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                _button_DastanSave.Content = "Timeout";
            }
            else if (e.Error != null)
            {
                _button_DastanSave.Content = "Error";
            }
            else
            {
                _button_DastanSave.Content = "Save";
            }
            _button_DastanSave.IsEnabled = true;
        }
        

        private void ButtonDastanClosePosition_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Dastan.DastanStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Dastan.DastanStock;
            if (strategy != null)
            {
                strategy.ExitUnit(DateTime.Now);
            }
        }
        private void ButtonDastanRemove_Click(object sender, RoutedEventArgs e)
        {
            //Do whatever you wanted to do with MyObject.ID
            Algobox.Structure.Finance.Strategies.Dastan.DastanStock strategy = ((FrameworkElement)sender).DataContext as Algobox.Structure.Finance.Strategies.Dastan.DastanStock;
            if (strategy != null)
            {
                _zephyrLoader.Dastan_Remove(strategy);
            }
        }
        
        private void ComboBox_DastanStock_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(((ComboBox)sender).IsDropDownOpen)
                _comboBox_DastanIndex.SelectedIndex = -1;
            e.Handled = true;
        }

        private void ComboBox_DastanIndex_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).IsDropDownOpen) 
                _comboBox_DastanStock.SelectedIndex = -1;
            e.Handled = true;
        }                


        #endregion


        private void SortDataGrid(object sender, DataGridSortingEventArgs e)
        {
            DataGrid dg = sender as DataGrid;
            if (dg != null)
            {
                e.Handled = true;
                ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ?
                                     ListSortDirection.Ascending : ListSortDirection.Descending;
                e.Column.SortDirection = direction;
                ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg.ItemsSource);
                ZephyrDataGridSorter mySort = new ZephyrDataGridSorter(direction, e.Column);
                lcv.CustomSort = mySort;
            }
        }
        
    }
}
